﻿/**************************************************************************
创建时间:	2020/6/28 11:22:26    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) zhcun.cn

描	述：
记	录：
***************************************************************************/
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZhCun.WebUtils.Authorizes;
using ZhCun.WebUtils.Configs;

namespace ZhCun.WebUtils
{
    public class UserPageAuthorizeAttribute : UserAuthorizeAttribute
    {
        public UserPageAuthorizeAttribute(bool isAuth = true)
        {
            IsAuth = isAuth;
        }

        protected override void AuthorizationHandle(AuthorizationFilterContext context)
        {
            if (!context.IsEffectivePolicy(this)) return;

            if (!IsAuth) return;

            var token = context.HttpContext.GetToken();
            if (!LoginState.CheckToken(token, out CurrUser))
            {
                //跳转至登陆页面
                context.HttpContext.Response.Redirect(CommonConfig.THIS.LoginPageUrl);
                context.Result = new EmptyResult();
                return;
            }

            if (DateTime.Now > CurrUser.ExpiresTime.Add(CurrUser.Expires * -0.8))
            {
                //每20%的过期时长 更新一次token
                var newToken = LoginState.RefreshToken(token);
                context.HttpContext.SetCookie(CommonConfig.THIS.TokenName, newToken, DateTime.Now.Add(CurrUser.Expires));
            }
        }
    }
}